package com.yzq.os.spider.v.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

/**
 * IP工具类
 * @author 苑志强(xingyu_yzq@163.com)
 *
 */
public final class IPUtils {
	
	private IPUtils(){}

	/**
	 * IP地址正则表达式
	 */
	private static final String VALID_IP_ADDRESS_REGEX = "\\d+\\.\\d+\\.\\d+\\.\\d+";

	/**
	 * 获取本机IP地址集合
	 * @return
	 */
	private static Collection<InetAddress> getAllHostAddress() {
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			Collection<InetAddress> addresses = new ArrayList<InetAddress>();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfaces.nextElement();
				Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					InetAddress inetAddress = inetAddresses.nextElement();
					addresses.add(inetAddress);
				}
			}
			return addresses;
		} catch (SocketException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 获取本机IP地址不包含回环地址
	 * @return
	 */
	public static List<String> getLocalIPAddress() {
		List<String> noLoopbackAddresses = new ArrayList<String>();
		Collection<InetAddress> allInetAddresses = getAllHostAddress();
		if(CollectionUtils.isNotEmpty(allInetAddresses)){
			for (InetAddress address : allInetAddresses) {
				if (!address.isLoopbackAddress()) {
					String ip = address.getHostAddress();
					if (Regex.isMatch(VALID_IP_ADDRESS_REGEX, ip)) {
						noLoopbackAddresses.add(ip);
					}
				}
			}
		}
		return noLoopbackAddresses;
	}

	/**
	 * 获取本机的第一个IP地址
	 * @return
	 */
	public static String getFirstLocalIPAddress() {
		String result = null;
		Collection<String> ips = getLocalIPAddress();
		if (CollectionUtils.isNotEmpty(ips)) {
			Iterator<String> ipIt=ips.iterator();
			if(ipIt.hasNext()){
				result = ipIt.next();
			}
		}
		return result;
	}
}